package cryptotools

import (
	"bytes"
	"crypto/sha256"
	"encoding/binary"
	"errors"
)

const MODULUS = int64(999999937)
const BASE = int64(97)

//与协商密钥相关的内容，例如数字签名，加密解密，哈希函数

//计算一个字符串的SHA256编码

func Power(base, exp int64) int64 {
	var temp = base % MODULUS
	var result int64 = 1
	for exp > 0 {
		if (exp & 1) != 0 {
			result = (result * temp) % MODULUS
		}
		temp = (temp * temp) % MODULUS
		exp >>= 1
	}
	return result
}

func Bytes32ToInt32(byteArr [32]byte) int32 {
	var i32 int32
	buf := bytes.NewReader(byteArr[:])
	binary.Read(buf, binary.BigEndian, &i32)
	return i32
}

func Bytes8ToInt64(byteArr []byte) (int64, error) {
	var i32 int64
	if len(byteArr) != 8 {
		return 0, errors.New("入参不是64bits,8bytes的数组")
	}
	buf := bytes.NewReader(byteArr[:])
	err := binary.Read(buf, binary.BigEndian, &i32)
	if err != nil {
		return 0, err
	}
	return i32, nil
}

func Int32ToBytes(num int32) []byte {
	bytesArr := make([]byte, 4)
	binary.BigEndian.PutUint32(bytesArr, uint32(num))
	return bytesArr
}

func Int64ToBytes(num int64) []byte {
	bytesArr := make([]byte, 8)
	binary.BigEndian.PutUint64(bytesArr, uint64(num))
	return bytesArr
}

func GetSHA256(text []byte) int32 {
	return Bytes32ToInt32(sha256.Sum256(text))
}

func CheckSHA256(text []byte, hashed int32) bool {
	return GetSHA256(text) == hashed
}
